<?php

class My_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{
    protected $_auth = null;
    protected $_acl = null;

    public function __construct(Zend_Auth $auth, Zend_Acl $acl)
    {
        $this->_auth = $auth;
        $this->_acl = $acl;
    }

    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        
        if ($this->_auth->hasIdentity()) {
            $username = $this->_auth->getIdentity()->username;
            $tblAccount = new Account();
            $select = $tblAccount->select()->where('username like ?',$username)
                                                ->where('status = ?', 1);
            $accountRow = $tblAccount->fetchRow($select);
            $role_id = $accountRow->role_id;

            switch ($role_id) {
                case 1:
                    $role = 'administrator';
                    break;
                case 2:
                    $role = 'member';
                    break;
            }
        } else {
            $role = 'guest';
        }

        $request = $this->getRequest();
        $resource = $request->module;
        

        // ACL Access Check
        if (!$this->_acl->isAllowed($role, $resource))
        {         
            if ($this->_auth->hasIdentity()) {
                // authenticated, denied access, forward to index
                $request->setModuleName('default');
                $request->setControllerName('index');
                $request->setActionName('denied');
            } else {
                // not authenticated, forward to login form
                $request->setModuleName('default');
                $request->setControllerName('index');
                $request->setActionName('login');
            }
        }
        
    }
}




